<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>
                    {{pageTitle}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <acc-set-card></acc-set-card>
        <div class="container" :style="{'min-height': containerHeight + 'px'}">
            <div class="handle-box flex flex-center">
                <el-button type="primary" icon="el-icon-folder" @click="saveEdit()">保存</el-button>
            </div>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="科目代码">
                            <el-input placeholder="请输入" v-model="ruleForm.subCode"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="上级科目" prop="parentSubId" v-if="!isUpdate">
                            <el-cascader
                                ref="cascaderAddr"
                                v-model="ruleForm.parentSubId"
                                :options="tableData"
                                :props="defaultProps"
                                :show-all-levels="false"
                                clearable
                                @change="handleChange"
                            >
                                <template slot-scope="{ node, data }">
                                    <span>{{ data.subName }}</span>
                                     <span> ({{ data.subCode }}) </span>
                                </template>
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="科目名称" placeholder="请输入" prop="subName">
                            <el-input v-model="ruleForm.subName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="科目属性" v-if="!isUpdate">
                            <el-input v-model="ruleForm.categoryName" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="余额方向" prop="drFlag" v-if="!isUpdate">
                            <el-select v-model="ruleForm.drFlag" placeholder="请选择">
                                <el-option label="借方" :value="1"></el-option>
                                <el-option label="贷方" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="结转损益" v-if="!isUpdate">
                            <el-select v-model="ruleForm.prolossFlag" placeholder="请选择">
                                <el-option label="自动结转" :value="1"></el-option>
                                <el-option label="不结转" :value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="科目性质" v-if="!isUpdate">
                            <el-select v-model="ruleForm.type" placeholder="请选择" disabled>
                                <el-option label="总账科目" :value="1"></el-option>
                                <el-option label="明细科目" :value="2"></el-option>
                                <el-option label="独立科目" :value="3"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="科目层级" v-if="!isUpdate">
                            <el-input v-model="ruleForm.level" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="核算外币" v-if="!isUpdate">
                            <el-switch
                                v-model="ruleForm.currFlag"
                                :active-value="1"
                                :inactive-value="0"
                                inactive-text="否"
                                active-text="是"
                            ></el-switch>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="核算人员" v-if="!isUpdate">
                            <el-switch
                                v-model="ruleForm.empFlag"
                                :active-value="1"
                                :inactive-value="0"
                                inactive-text="否"
                                active-text="是"
                            ></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="6">
                        <el-form-item label="核算部门" v-if="!isUpdate">
                            <el-switch
                                v-model="ruleForm.deptFlag"
                                :active-value="1"
                                :inactive-value="0"
                                inactive-text="否"
                                active-text="是"
                            ></el-switch>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="核算往来" v-if="!isUpdate">
                            <el-switch
                                v-model="ruleForm.dealFlag"
                                :active-value="1"
                                :inactive-value="0"
                                inactive-text="否"
                                active-text="是"
                            ></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="核算项目" v-if="!isUpdate">
                            <el-switch
                                v-model="ruleForm.proFlag"
                                :active-value="1"
                                :inactive-value="0"
                                inactive-text="否"
                                active-text="是"
                            ></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </div>
</template>


<script>
import appMain from '../../../utils/app_main';
import _ from 'lodash';
import XEUtils from 'xe-utils';

export default {
    data() {
        return {
            pageTitle: '',
            containerHeight: '',
            tableData: [],
            rules: {
                subName: [
                    { required: true, message: '请输入科目名称', trigger: 'blur' },
                    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
                ],
                drFlag: [{ required: true, message: '请选择余额方向', trigger: 'change' }],
                prolossFlag: [{ required: true, message: '请选择结转损益', trigger: 'change' }]
            },
            defaultProps: {
                label: 'subName',
                value: 'id',
                children: 'child',
                checkStrictly: true
            },
            isUpdate: false,
            ruleForm: {
                categoryId: '', //科目类别Id
                categoryName: '', //科目类别名字
                currFlag: 2, //是否核算外币：0:否  1是-
                dealFlag: 2, //是否合算往来单位：0否，1是
                deptFlag: 2, //是否核算部门:0否，1是
                subName: '', //科目名称
                drFlag: 1, //余额方向	1.借方 2.贷方
                empFlag: 2, //是否核算人员：0否，1是
                level: 99, //科目层级:接口返回
                parentSubId: '', //上级科目
                proFlag: 2, //是否合算项目：0否，1是
                prolossFlag: 1, //结转损益方向：1.自动转出（结算没有余额） 2.不转出（结算有余额）
                type: 3 //科目性质:接口返回
            }, //新增model
            editForm: {}
        };
    },
    created() {
        if (this.$route.query.id) {
            let id = this.$route.query.id;
            //this.ruleForm = JSON.parse(this.$route.query.ruleForm);
            //是更新操作
            this.isUpdate = true;
            //查询科目详情
            this.getDataById(id);
        } else {
            //新增操作
            let categoryId = this.$route.query.categoryId;
            //this.ruleForm = JSON.parse(this.$route.query.ruleForm);
            console.log('ruleForm', this.$route.query.ruleForm);
            this.isUpdate = false;
            this.subjectGetTreeByType(categoryId);
            this.getByCateId(categoryId);
        }
    },
    mounted() {
        var div_height = window.screen.availHeight;
        var height = div_height - 100;
        this.containerHeight = height - 200;
        this.pageTitle = this.$router.currentRoute.meta.title;
        //$refs.xTree.setAllTreeExpand(true);
    },
    methods: {
        //获取科目属性
        getByCateId(id) {
            appMain
                .subjectCategoryFindById({}, id)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.ruleForm.categoryName = res.data.data.description;
                        this.ruleForm.categoryId = res.data.data.categoryId;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        //获取科目
        getDataById(id) {
            appMain
                .subjectFindById({}, id)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.ruleForm = res.data.data;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        addSubject() {
            appMain
                .subjectInsert(this.ruleForm)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.$message.success(res.data.message);
                        this.$router.push({
                            path: '/subjectManagement' //跳转的路径
                        });
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        updateSubject() {
            appMain
                .subjectUpdateById(this.ruleForm)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.$message.success(res.data.message);
                        this.$router.push({
                            path: '/subjectManagement' //跳转的路径
                        });
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        handleChange(value) {
            //var categoryName = this.$refs['cascaderAddr'].inputValue;
            var currentLabels = this.$refs['cascaderAddr'].getCheckedNodes();
            var data = currentLabels[0].data;
            console.log('currentLabels', data);

            if (data.level == 99) {
                this.ruleForm.level = 2;
                this.ruleForm.type = 2;
            } else if (1 <= data.level || data.level < 98) {
                this.ruleForm.level = data.level + 1;
                this.ruleForm.type = 2;
            }

            this.ruleForm.parentSubId = value[value.length - 1];
            console.log('handleChange', value);
        },
        submitForm(formName) {
            this.$refs['ruleForm'].validate(valid => {
                if (valid) {
                    if (formName == 'ruleForm') {
                        //新增科目
                        this.addSubject();
                    } else if (formName == 'editForm') {
                        this.updateSubject();
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        saveEdit() {
            if (this.isUpdate == false) {
                this.submitForm('ruleForm');
            } else if (this.isUpdate == true) {
                this.submitForm('editForm');
            }
        },
        //根据科目属性获取科目列表
        subjectGetTreeByType(categoryId) {
            appMain
                .subjectGetTreeByType({}, categoryId)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.tableData = res.data.data;
                        //this.ruleForm.categoryName = res.data.data[0].categoryName;
                        //this.ruleForm.categoryId = res.data.data[0].categoryId;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        }
    },
    computed: {
        //上级科目id
        getParentSubId: function() {
            return this.ruleForm.parentSubId;
        }
    },
    watch: {
        getParentSubId: {
            handler: function() {
                if (this.ruleForm.parentSubId == '') {
                    this.level = 99;
                    this.type = 1;
                }
                console.log('getParentSubId', this.ruleForm);
            }
        }
    }
};
</script>

<style lang="css" scoped>
.el-card {
    height: 100%;
}

.handle-box {
    padding: 5px 50px;
    width: 100%;
    background-color: #fff;
    position: absolute;
    left: 0;
    bottom: 0px;
    border-bottom: 1px solid #ddd;
    border-top: 1px solid #ddd;
    z-index: 1;
}

.el-input {
    max-width: 215px;
}
</style>